import collections


class Solution(object):
    def calculate(self, s):
        """
        :type s: str
        :rtype: int
        """
        stack = collections.deque()
        stack.append(collections.deque())
        state = 0
        left_index = 0
        right_index = 0
        last = collections.deque([0])
        n = len(s)
        while right_index < n:
            if s[right_index] == '(':
                stack.append(collections.deque())
                last.append(0)
                left_index += 1
            if s[right_index] == '+':
                if right_index - left_index > 0:
                    num = int(s[left_index: right_index])
                    if last[-1]:
                        num = - num
                    stack[-1].append(num)
                left_index = right_index + 1
                last[-1] = 0
            if s[right_index] == '-':
                if right_index - left_index > 0:
                    num = int(s[left_index: right_index])
                    if last[-1]:
                        num = - num
                    stack[-1].append(num)
                left_index = right_index + 1
                last[-1] = 1
            if s[right_index] == ')':
                if right_index - left_index > 0:
                    num = int(s[left_index: right_index])
                    if last[-1]:
                        num = - num
                    stack[-1].append(num)
                num = sum(stack[-1])
                stack.pop()
                last.pop()
                if last[-1]:
                    num = - num
                stack[-1].append(num)
                left_index = right_index + 1
            if s[right_index] == ' ':
                if right_index - left_index > 0:
                    num = int(s[left_index: right_index])
                    if last[-1]:
                        num = - num
                    stack[-1].append(num)
                left_index = right_index + 1
            right_index += 1
        if right_index - left_index > 0:
            num = int(s[left_index: right_index])
            if last[-1]:
                num = - num
            stack[0].append(num)
        return sum(stack[0])


data = Solution()
s = "1 + 1"
print(data.calculate(s))
s = " 2-1 + 2 "
print(data.calculate(s))
s = "(1+(4+5+2)-3)+(6+8)"
print(data.calculate(s))